package com.habdqn.studentmanager.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageInfo;
import com.github.xiaofan1519.verify.core.Verify;
import com.github.xiaofan1519.verify.exception.VerifyException;
import com.habdqn.studentmanager.bean.Dictionary;
import com.habdqn.studentmanager.bean.SysLog;
import com.habdqn.studentmanager.bean.Teacher;
import com.habdqn.studentmanager.bean.condition.DateCondition;
import com.habdqn.studentmanager.constant.Constant;
import com.habdqn.studentmanager.constant.DictType;
import com.habdqn.studentmanager.constant.FieldDefine;
import com.habdqn.studentmanager.constant.LogType;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.service.SystemService;
import com.habdqn.studentmanager.util.MD5Util;
import com.habdqn.studentmanager.util.ProjectUtil;
import com.habdqn.studentmanager.util.SystemLogger;

/**
 * @author Administrator
 * 
 *         2017年5月15日
 * 
 */
@Controller
@RequestMapping("/system")
public class SystemController {

    private static Logger logger = LoggerFactory.getLogger(SystemController.class);

    /**
     * 系统服务类
     */
    @Resource
    private SystemService systemService;

    @Resource
    private SystemLogger systemLogger;
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Teacher bean, @RequestParam(required = false) String remember, Model attr) {

        // 校验
        try {
            Verify.verifyEmpty(bean.getAccount());
            Verify.verifyEmpty(bean.getPassword());
        }
        catch (VerifyException e) {
            // 提示错误信息
            attr.addAttribute(Constant.ERROR_MSG, "账号或密码为空");
            return "login";
        }

        boolean isRemember = false;
        if (StringUtils.equals("on", remember)) {
            isRemember = true;
        }

        try {
            systemService.login(bean, isRemember);
        }
        catch (StudentException e) {
            logger.debug("login faild. account = {}", bean.getAccount(), e);
            attr.addAttribute(Constant.ERROR_MSG, e.getMessage());
            systemLogger.record(LogType.LoginType, "登录失败:" + bean.getAccount());
            return "login";
        }
        catch (RuntimeException e) {
            logger.debug("login faild.", e);
            attr.addAttribute(Constant.ERROR_MSG, "登录失败, 系统错误");
            systemLogger.record(LogType.LoginType, "登录失败:" + bean.getAccount());
            return "login";
        }
        
        // 登录成功
        return "redirect:/";
    }

    /**
     * 退出登录
     * 
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String exit(Model model) {
        try {
            systemService.exit();
        }
        catch (StudentException e) {
            logger.debug("退出失败.", e);
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }
        return "redirect:/login";
    }

    /**
     * 去修改密码页面
     * 
     * @return
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.GET)
    public String toChangePassword() {

        return "sys/changePassword";
    }

    /**
     * 修改密码
     * 
     * @param oldPassword
     *            当前密码
     * @param confirmPassword
     *            确认密码
     * @param newPassword
     *            新密码
     * @param attr
     * @return
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public String changePassword(String oldPassword, String confirmPassword, String newPassword, Model attr) {

        // 校验
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(confirmPassword)
                || StringUtils.isEmpty(newPassword)) {

            attr.addAttribute(Constant.ERROR_MSG, "必填参数为空");
            return "sys/changePassword";
        }

        // 校验确认密码是否和新密码一致
        if (!StringUtils.equals(confirmPassword, newPassword)) {
            attr.addAttribute("error", "两次密码不一致");
            return "sys/changePassword";
        }

        try {
            Teacher teacher = ProjectUtil.getCurrentUser();

            // MD5(账号+密码明文)加密保存
            oldPassword = MD5Util.getMD5(teacher.getAccount() + oldPassword);
            newPassword = MD5Util.getMD5(teacher.getAccount() + newPassword);
            systemService.changePassword(oldPassword, newPassword);
        }
        catch (StudentException e) {
            logger.debug(e.getMessage(), e);
            attr.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return "sys/changePassword";
        }
        catch (Exception e) {
            logger.error("system error.", e);
            attr.addAttribute(Constant.ERROR_MSG, "系统错误");
            return "sys/changePassword";
        }

        attr.addAttribute("success", "修改成功");
        return "sys/changePassword";
    }

    @RequestMapping("/logList")
    public String logList(SysLog bean, DateCondition dateCondition, @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "30") Integer pageSize, Model model) {

        if (null == pageNum) {
            pageNum = 1;
        }

        if (null == pageSize) {
            pageSize = 10;
        }

        // 查询日志类型
        List<Dictionary> logTypes = null;
        PageInfo<SysLog> pageInfo = null;

        try {
            logTypes = systemService.findDictList(Dictionary.make(DictType.LogType, null, null));
            pageInfo = systemService.findLogList(bean, dateCondition, pageNum, pageSize);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return "error";
        }

        Integer typeValue = null;
        if (null != bean && null != bean.getType()) {
            typeValue = bean.getType().getValue();
        }

        model.addAttribute("logTypes", logTypes);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("logType", typeValue);
        model.addAttribute("dateCondition", dateCondition);
        return "sys/logList";
    }

    /**
     * 跳转至注册页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String toRegister(Model model) {

        List<Dictionary> teacherTypes = null;

        try {
            teacherTypes = systemService.findDictList(Dictionary.make(DictType.TeacherType, null, null));
        }
        catch (StudentException e) {
            logger.error("system error", e);
            model.addAttribute(Constant.ERROR_MSG, "获取教师类型失败");
            return Constant.ERROR_PAGE;
        }

        model.addAttribute("types", teacherTypes);

        return "register";
    }

    /**
     * 账号注册
     * 
     * @param bean
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(Teacher bean, Model model) {

        try {
            Verify.verifyNull(bean);

            Verify.verifyLen(bean.getAccount(), FieldDefine.MIN_PASSWD_LENTH, FieldDefine.MAX_PASSWD_LENTH);
            Verify.verifyLen(bean.getName(), FieldDefine.MIN_NAME_LENGTH, FieldDefine.MAX_NAME_LENGTH);

            Verify.verifyLenAllowEmpty(bean.getTel(), FieldDefine.MIN_TEL_LENTH, FieldDefine.MAX_TEL_LENTH);

            Verify.verifyNull(bean.getType());
            Verify.verifyNull(bean.getType().getValue());
            Verify.verifyLenAllowEmpty(bean.getRemarks(), FieldDefine.MIN_REMARKS_LENTH, FieldDefine.MAX_REMARKS_LENTH);

            Verify.verifyEmailAllowEmpty(bean.getEmail());

            Verify.verifyLenAllowEmpty(bean.getRemarks(), FieldDefine.MIN_REMARKS_LENTH, FieldDefine.MAX_REMARKS_LENTH);
        }
        catch (VerifyException e) {
            logger.debug("参数校验失败", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
        	throw new StudentException("未开放");
            // systemService.register(bean);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        // model.addAttribute(Constant.ERROR_MSG, "注册成功!");
        // model.addAttribute("href", "login");
        // return "success";
    }

}
